package com.zlll.winner.controller.mall;

import com.alibaba.fastjson.JSONObject;
import com.zlll.winner.business.model.mall.MallSelectGoods;
import com.zlll.winner.business.service.mall.IMallSelectGoodsService;
import com.zlll.winner.common.BaseController;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/mallSelectGoods")
public class MallSelectGoodsController extends BaseController {

    @Reference
    private IMallSelectGoodsService mallSelectGoodsService;

    @PostMapping("getPage")
    public Object getPage(@RequestBody JSONObject data) {
        Integer pageNo = data.getInteger("pageNo") == null ? 1 : data.getInteger("pageNo");
        Integer pageSize = data.getInteger("pageSize") == null ? 20 : data.getInteger("pageSize");
        String goodsName = data.getString("goodsName");
        return mallSelectGoodsService.getPage(goodsName, pageSize, pageNo);
    }

    @PostMapping("add")
    public Object add(@RequestBody MallSelectGoods goods) throws Exception {
        goods.setUpdateUser(getUser().getId().toString());
        List list = mallSelectGoodsService.isRepeat(goods.getGoodsId());
        if (list.size() > 0) {
            throw new Exception("该商品已经设置为星选商品了");
        }
        return mallSelectGoodsService.add(goods);
    }

    @PostMapping("get/{id}")
    public Object getInfoById(@PathVariable Long id) {
        return mallSelectGoodsService.getMallSelectGoodsVoById(id);
    }

    @PostMapping("edit")
    public Object edit(@RequestBody MallSelectGoods goods) throws Exception {
        goods.setUpdateUser(getUser().getId().toString());
        List<MallSelectGoods> list = mallSelectGoodsService.isRepeat(goods.getGoodsId());
        if (list.size() > 1) {
            throw new Exception("该商品已经设置为星选商品了");
        } else if (list.size() == 1) {
            if (!goods.getId().equals(list.get(0).getId())) {
                throw new Exception("该商品已经设置为星选商品了");
            }
        }
        return mallSelectGoodsService.edit(goods);
    }

    @PostMapping("updateStatus")
    public Object updateStatus(@RequestBody JSONObject data){
        Long id = data.getLong("id");
        MallSelectGoods goods =mallSelectGoodsService.getById(id);
        goods.setStatus(0);
        goods.setUpdateTime(System.currentTimeMillis());
        goods.setUpdateUser(getUserId().toString());
        mallSelectGoodsService.updateById(goods);
        return goods;
    }
}
